/**
 *  工具函数封装
 **/
/**
 *
 * @param  {function}   func      回调函数
 * @param  {number}     wait      表示时间窗口的间隔
 * @param  {boolean}    immediate 是否立即执行 
 *                               
 * @return {function}             返回调用函数
 */
export let debounce = (func, wait = 200, immediate = false) => {
  let timer, ctx, args;
  // 延迟执行函数
  const later = () => setTimeout(() => {
    timer = null;
    if (!immediate) {
      func.call(ctx, ...args);
      ctx = args = null;
    }
  }, wait);

  return function () {
    if (!timer) {
      timer = later();
      if (immediate) {
        func.call(this, ...arguments);
      } else {
        ctx = this;
        args = arguments;
      }
    } else {
      clearTimeout(timer);
      timer = later();
    }
  }
}
//保存图片到相册
export const writePhotosAlbum = (successFun, failFun) => {
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: function () {
            successFun && successFun()
          },
          fail: function (res) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: "小程序需要您的微信授权保存图片，是否重新授权？",
              showCancel: true,
              cancelText: "否",
              confirmText: "是",
              success: function (res2) {
                if (res2.confirm) { //用户点击确定'
                  wx.openSetting({
                    success: (res3) => {
                      if (res3.authSetting['scope.writePhotosAlbum']) {
                        //已授权
                        successFun && successFun()
                      } else {
                        failFun && failFun()
                      }
                    }
                  })
                } else {
                  failFun && failFun()
                }
              }
            });
          }
        })
      } else {
        successFun && successFun()
      }
    }
  })
}

/* @description 正则验证
 * @param {String} val 要验证的值
 * @param {String} type 要验证的类型
 * [type可能的值为：notEmpty值不为空、phone手机号、sixFigures六位数字]
 * 根据需求继续扩展
 **/
export const u_Reg = (val, type) => {
  switch (type) {
    // 值不为空
    case 'notEmpty':
      return val && val.length > 0 && !/^\s/.test(val);
      break;
    // 验证手机号
    case 'phone':
      return /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(val);
      break;
    // 六位数字  
    case 'sixFigures':
      return /^\d{6}$/.test(val);
      break;
    // 登录密码  
    case 'loginPass':
      return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@&%$^\\(\\)#_.]{6,16}$/.test(val);
      break;
    default:
      alert('函数type参数不匹配');
      break;
  }
}

/* @description 格式化剩余时间
 * @param {String} endTime 结束日期
 * @return {Object} d:剩余天数、h:小时数、m:分钟数、s:秒数
 **/
export const u_formatRemainTime = (endTime) => {
  const startDate = new Date(), //开始时间
    endDate = new Date(endTime), //结束时间
    t = startDate.getTime() - endDate.getTime(); //时间差
  let d = 0,
    h = 0,
    m = 0,
    s = 0;

  if (t >= 0) {
    d = formatNumber(Math.floor(t / 1000 / 60 / 60 / 24));
    h = formatNumber(Math.floor(t / 1000 / 60 / 60 % 24));
    m = formatNumber(Math.floor(t / 1000 / 60 % 60));
    s = formatNumber(Math.floor(t / 1000 % 60));
  }
  return {
    d, h, m, s
  }
}

/* @description 时间戳转换
 * @param {String} time 要转换的时间戳
 * @param {String} conf 配置参数
 * @return {Object} "all"返回年月日时分秒，"ymd"返回年月日，"ymdhm"返回年月日时分
 **/
export const u_formatTimestamp = (time, conf) => {
  let config = Object.assign({
    type: 'all', // 转换类型，"all"、"ymd"、"md"、"ymdhm"、"hm"
    markFrot: "-", // 年月日的连接符，默认“-”
    markBack: ":" // 时分秒的连接符，默认“:”
  }, conf);
  let startDate = new Date() //开始时间
  let terday = formatNumber(startDate.getDate())
  let date = new Date(time),
      year = date.getFullYear(),
      month = formatNumber(date.getMonth() + 1),
      day = formatNumber(date.getDate()),
      hour = formatNumber(date.getHours()),
      minute = formatNumber(date.getMinutes()),
      second = formatNumber(date.getSeconds());
  switch (config.type) {
    case "d":
      return terday - day;
      break;
    case "ymd":
      return `${year}${config.markFrot}${month}${config.markFrot}${day}`;
      break;
    case "md":
      return `${month}月${day}日`;
      break;
    case "ymdhm":
      return `${year}${config.markFrot}${month}${config.markFrot}${day} ${hour}${config.markBack}${minute}`;
      break;
    case "ymdhm2":
      return `${year}年${month}月${day}日 ${hour}${config.markBack}${minute}`;
      break;
    case "hm":
      return `${hour}${config.markBack}${minute}`;
      break;
    default:
      return `${year}${config.markFrot}${month}${config.markFrot}${day} ${hour}${config.markBack}${minute}${config.markBack}${second}`;
      break;
  }
}

// 将一位数转换成0开头，例如： 1->01，0->09
export const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 10为数的时间戳
export const tenTimeStr = (time) => {
  let date = new Date(time * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  // let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  let D = date.getDate() + '日';
  // let h = date.getHours() + ':';
  // let m = date.getMinutes() + ':';
  // let s = date.getSeconds();
  return M + D;
}

//倒计时
export const count = e => {
  var time = Number(e);
  //天
  // var day = this.formatNumber(parseInt(time / 60 / 60 / 24));
  // time = parseInt(time / 60 / 60 / 24) > 0 ? time % (day * 60 * 60 * 24) : time;
  // 时
  var hour = formatNumber(parseInt(time / 60 / 60) > 0 ? parseInt(time / 60 / 60) : 0);
  time = time % (hour * 60 * 60) > 0 ? time % (hour * 60 * 60) : time;
  // 分
  var minute = formatNumber(parseInt(time / 60) > 0 ? parseInt(time / 60) : 0);
  time = time % 60;
  // 秒
  var second = formatNumber(time);
  var cons = [hour, minute, second]
  return cons;
}

/**
 * 将数字保留n位小数
*/
export const u_fixed = (val, n = 2) => {
  return (val - 0).toFixed(n);
}

//计算两点之间的距离
export const getLocation = (lat1, lng1, lat2, lng2) => { lat1 = lat1 || 0; lng1 = lng1 || 0; lat2 = lat2 || 0; lng2 = lng2 || 0; var rad1 = lat1 * Math.PI / 180.0; var rad2 = lat2 * Math.PI / 180.0; var a = rad1 - rad2; var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0; var r = 6378137; return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0) }